package com.ruoyi.web.ydz.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.web.ydz.domain.GradeRule;
import com.ruoyi.web.ydz.domain.PointsRecord;
import com.ruoyi.web.ydz.domain.PointsRule;
import com.ruoyi.web.ydz.domain.UserDocument;
import com.ruoyi.web.ydz.mapper.PointsRecordMapper;
import com.ruoyi.web.ydz.mapper.PointsRuleMapper;
import com.ruoyi.web.ydz.mapper.UserDocumentMapper;
import com.ruoyi.web.ydz.service.IGradeRuleService;
import com.ruoyi.web.ydz.service.IPointsRecordService;
import com.ruoyi.web.ydz.util.messageUtil.SendSms;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 用户签到及积分收入记录Service业务层处理
 *
 * @author ruoyi
 * @date 2024-11-22
 */
@Service
public class PointsRecordServiceImpl implements IPointsRecordService {
    @Resource
    private PointsRecordMapper pointsRecordMapper;

    @Resource
    private PointsRuleMapper pointsRuleMapper;

    @Resource
    private UserDocumentMapper userDocumentMapper;

    @Resource
    private SendSms sendSms;

    @Resource
    private IGradeRuleService gradeRuleService;

    /*积分操作记录类型 : 签到*/
    public static final Long Sign_in_type = 1L;

    /**
     * 查询用户签到及积分收入记录
     *
     * @param id 用户签到及积分收入记录主键
     * @return 用户签到及积分收入记录
     */
    @Override
    public PointsRecord selectPointsRecordById(Long id) {
        return pointsRecordMapper.selectPointsRecordById(id);
    }

    /**
     * 查询用户签到及积分收入记录列表
     *
     * @param pointsRecord 用户签到及积分收入记录
     * @return 用户签到及积分收入记录
     */
    @Override
    public List<PointsRecord> selectPointsRecordList(PointsRecord pointsRecord) {
        return pointsRecordMapper.selectPointsRecordList(pointsRecord);
    }

    /**
     * 新增用户签到及积分收入记录
     *
     * @param pointsRecord 用户签到及积分收入记录
     * @return 结果
     */
    @Override
    public int insertPointsRecord(PointsRecord pointsRecord) {
        pointsRecord.setCreateTime(DateUtils.getNowDate());
        return pointsRecordMapper.insertPointsRecord(pointsRecord);
    }

    /**
     * 修改用户签到及积分收入记录
     *
     * @param pointsRecord 用户签到及积分收入记录
     * @return 结果
     */
    @Override
    public int updatePointsRecord(PointsRecord pointsRecord) {
        pointsRecord.setUpdateTime(DateUtils.getNowDate());
        return pointsRecordMapper.updatePointsRecord(pointsRecord);
    }

    /**
     * 批量删除用户签到及积分收入记录
     *
     * @param ids 需要删除的用户签到及积分收入记录主键
     * @return 结果
     */
    @Override
    public int deletePointsRecordByIds(Long[] ids) {
        return pointsRecordMapper.deletePointsRecordByIds(ids);
    }

    /**
     * 删除用户签到及积分收入记录信息
     *
     * @param id 用户签到及积分收入记录主键
     * @return 结果
     */
    @Override
    public int deletePointsRecordById(Long id) {
        return pointsRecordMapper.deletePointsRecordById(id);
    }

    /*签到*/
    @Override
    @Transactional
    public AjaxResult signIn() {

        AjaxResult ajaxResult = new AjaxResult();

        try {

            SysUser user = SecurityUtils.getLoginUser().getUser();
            if (Objects.isNull(user)) {
                ajaxResult.put("code", 200);
                ajaxResult.put("msg", "未知用户信息,请联系管理员");
                return ajaxResult;
            }

            /*查询当前用户当日是否已签到*/
            PointsRecord checkSing = pointsRecordMapper.checkSignIn(user.getUserId());

            if (!Objects.isNull(checkSing)) {
                ajaxResult.put("code", 200);
                ajaxResult.put("msg", "您今日已签到,无需重复签到");
                return ajaxResult;
            }

            /*获取签到的积分奖励*/
            PointsRule pointsRule = pointsRuleMapper.selectPointsRuleById(Sign_in_type);
            Long pointsNum = pointsRule.getPointsNum();

            PointsRecord pointsRecord = new PointsRecord();
            pointsRecord.setRuleId(Sign_in_type);
            pointsRecord.setPoints(pointsNum);
            pointsRecord.setUserId(user.getUserId());

            pointsRecord.setCreateTime(DateUtils.getNowDate());
            pointsRecord.setCreateBy(user.getUserName());
            pointsRecord.setCreateName(user.getNickName());

            pointsRecordMapper.insertPointsRecord(pointsRecord);

            /*更新用户总积分*/
            UserDocument userDocument = userDocumentMapper.selectUserDocumentByUserId(user.getUserId());
            if (Objects.isNull(userDocument)) {
                UserDocument ud = new UserDocument();
                ud.setUserId(user.getUserId());
                ud.setPoints(pointsNum);
                userDocumentMapper.insertUserDocument(ud);
            } else {
                userDocument.setPoints(userDocument.getPoints() + pointsNum);

                /*
                 * 检验用户是否升级
                 * 当前用户没有等级信息时 设置为等级1
                 * 等级只升不降
                 * */
                GradeRule gradeRule = gradeRuleService.checkGrade(userDocument.getPoints());
                if (!Objects.isNull(gradeRule) && !Objects.isNull(gradeRule.getLevel())) {
                    if (Objects.isNull(userDocument.getLevel())) userDocument.setLevel(1l);
                    if (gradeRule.getLevel().longValue() > userDocument.getLevel().longValue()) {
                        userDocument.setLevel(gradeRule.getLevel());
                        ajaxResult.put("upgrade", "恭喜您,升至 " + gradeRule.getLevel() + " 等级");
                    }
                }

                userDocumentMapper.updateUserDocument(userDocument);
            }

            ajaxResult.put("code", 200);
            ajaxResult.put("msg", "签到成功,获得" + pointsNum + "积分");
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("code", 500);
            ajaxResult.put("msg", "签到失败,请联系管理员");
        }

        return ajaxResult;
    }

    @Override
    public AjaxResult getSignInRecord() {

        AjaxResult ajaxResult = new AjaxResult();
        try {
            SysUser user = SecurityUtils.getLoginUser().getUser();
            if (Objects.isNull(user)) {
                ajaxResult.put("code", 200);
                ajaxResult.put("msg", "未知用户信息,请联系管理员");
                return ajaxResult;
            }

            List<Date> currentWeek = sendSms.getCurrentWeek();
            PointsRecord pointsRecord = new PointsRecord();
            pointsRecord.setCurrentWeek(currentWeek);
            pointsRecord.setUserId(user.getUserId());

            List<PointsRecord> signInRecord = pointsRecordMapper.getSignInRecord(pointsRecord);
            signInRecord.sort(Comparator.comparingInt(PointsRecord::getWeek));

            ajaxResult.put("code", 200);
            ajaxResult.put("msg", "查询成功");
            ajaxResult.put("data", signInRecord);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("code", 500);
            ajaxResult.put("msg", "查询失败,请联系管理员");
            ajaxResult.put("data", null);
            return ajaxResult;
        }

        return ajaxResult;
    }
}